package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-28 00:39
 **/
public class LeetCode438 {

    //优化后的滑动窗口
    public List<Integer> findAnagrams(String s, String p) {
        int lens = s.length();
        int lenp = p.length();

        List<Integer> list = new ArrayList<>();
        if (lens < lenp) {
            return list;
        }

        int[] counts = new int[26];
        int diff = 0;
        for (int i = 0; i < lenp; i++) {
            ++counts[s.charAt(i) - 'a'];
            --counts[p.charAt(i) - 'a'];
        }

        for (int i = 0; i < 26; i++) {
            if (counts[i] != 0) {
                diff++;
            }
        }

        if (diff == 0) {
            list.add(0);
        }

        for (int i = 0; i < lens - lenp; i++) {
            if (counts[s.charAt(i) - 'a'] == 1) {
                diff--;
            } else if (counts[s.charAt(i) - 'a'] == 0) {
                diff++;
            }
            --counts[s.charAt(i) - 'a'];
            if (counts[s.charAt(i + lenp) - 'a'] == -1) {
                diff--;
            } else if (counts[s.charAt(i + lenp) - 'a'] == 0) {
                diff++;
            }
            ++counts[s.charAt(i + lenp) - 'a'];
            if (diff == 0) {
                list.add(i + 1);
            }
        }
        return list;
    }

    //滑动窗口
    /*public List<Integer> findAnagrams(String s, String p) {
        int lens = s.length();
        int lenp = p.length();

        List<Integer> list = new ArrayList<>();
        if (lens < lenp) {
            return list;
        }

        int[] counts = new int[26];
        int[] countp = new int[26];
        for (int i = 0; i < lenp; i++) {
            ++counts[s.charAt(i) - 'a'];
            ++countp[p.charAt(i) - 'a'];
        }

        if (Arrays.equals(counts, countp)) {
            list.add(0);
        }

        for (int i = 0; i < lens - lenp; i++) {
            --counts[s.charAt(i) - 'a'];
            ++counts[s.charAt(i + lenp) - 'a'];
            if (Arrays.equals(counts, countp)) {
                list.add(i + 1);
            }
        }

        return list;
    }*/

}
